import 'package:get/get.dart';
import 'package:hive/hive.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'package:pass_log/app/core/utils/common.dart';
import 'package:pass_log/app/core/utils/encryption.dart';

typedef ObjItem = Map<String, dynamic>;

// 全局状态管理：密码列表
class PassListProvider extends GetxController {
  var box = Hive.box<String>(name: "pass"); // 打开存储密码的HiveBox
  var list = <ObjItem?>[].obs; // 密码列表

  // 更新密码列表
  void refreshPass() {
    var li = box.getAll(box.keys).map((item) {
      if (item != null) return Encryption.decryptPass(item);
    }).toList();
    if (li.length > 1) li.sort((a, b) => (int.parse(a!["id"])).compareTo(int.parse(b!["id"])));
    list.value = li;
  }

  // 删除密码
  void deletePass(ObjItem data) {
    box.delete(data["id"]);
    refreshPass();
    EasyLoading.showSuccess("删除成功");
  }

  // 编辑密码
  void editPass(ObjItem data) {
    box.put(data["id"], Encryption.encryptPass(data));
    refreshPass();
    EasyLoading.showSuccess("编辑成功").then((value) {
      Get.back();
    });
  }

  // 创建密码
  void createPass(ObjItem data) {
    var id = getUnixMilliseconds();
    box.put(id.toString(), Encryption.encryptPass({"id": id.toString(), ...data}));
    refreshPass();
    EasyLoading.showSuccess("保存成功").then((value) {
      Get.back();
    });
  }

  // 修改密码分类
  void changePassType(ObjItem data, String typeId) {
    box.put(data["id"], Encryption.encryptPass({...data, "type_id": typeId}));
  }
}
